/**
 * 通用列表模块
 * 
 * @Date: 2016-1-24
 * @author: Jackson wang
 * @version: 1.0
 * @since: 1.0
 */
define(["jquery", "msgServ","ajaxServ","datagridServ","sysmanMain","formServ",
	"btnServ","bizProto","buttonEvent"], 
	function($,msgServ,ajaxServ,datagridServ,sysmanMain,formServ,
		btnServ,bizProto,buttonEvent) {

	'use strict';

	var    $dg,$grid,$edit_window,$form,
			//搜索框和高级查找div
			$searchbox,$condition,
			_moduleConfig,_buttonConfig,_bizProto,_defaultConfig,
			config = {
				doc:null,
				rootId:null,				
				panelSelector:'div.well',
				subSystemCode:null,
				moduleCode:null,
				editWindow:null,
				listToolBar:'div.tb-list',
				querylistUrl:null,
				editPageUrl:null,
				queryModule:null,
				btnSelector:'td.list-btn',
				
				//初始查询条件
				initQueryParams:null,
				
				//初始化元素外部扩展函数
				initElement:null,
				
				//列表高度调整
				listHeightResize:null,
				
				//grid click event
				cellClick:null,
				
				rowClick:null,
				rowDblClick:null,
				
				conditionForm:'form.condition-form',
				//高级查询取值扩展函数
				conditionExtends:null,
				
				//窗口最大化
				maxWindowSize:false,
				
				edit_window_height:700,
				edit_window_width:900,
				pagination:true,
				buttonExtends:null,//按钮方法扩展
				onWindowClose:null, //window close event
				listInitialized:false
			}
    
	var	private_method = {
		init : function(_options) {
			
			_moduleConfig = sysmanMain.getCurrentModuConfig();
			
			if (window.console) {
				console.info(_moduleConfig.fullBizcode +' modules gets ready and been loaded.');
			}		
			
			
			_defaultConfig = $.extend({},config,_moduleConfig,_options)	
			
			//最大化窗口
			if(_defaultConfig.maxWindowSize){
				_defaultConfig.edit_window_height = $(document).height();
				_defaultConfig.edit_window_width = $(document).width();
			}
			
			_bizProto = new bizProto(_defaultConfig);			
			_bizProto.gridHeight -= 15
			
			
			_defaultConfig.bizProto = _bizProto
			
			if(_defaultConfig.editWindow){
				$edit_window = $('#' + _defaultConfig.editWindow);			
			}
			
			_buttonConfig={
				"新增":private_method.add,
			    "编辑":private_method.edit,
				"删除":private_method.del	,
				"导出当前页":function(){private_method.exportExcel()},
				"导出全部":function(){private_method.exportExcel({type:'all'})},
				'批量退回':function(){private_method.auditList({status:-1})},
				'批量审核':function(){private_method.auditList({status:1})},
				'批量提交':function(){private_method.auditList({status:0})},
				"查询条件":private_method.conditionQuery,
				"执行查询":private_method.doSearch
			}
			//扩展按钮方法
			if(_defaultConfig.buttonExtends){
				var _extends = _defaultConfig.buttonExtends()
				if(_extends)
				$.extend(_buttonConfig,_extends)
			}
			
			_defaultConfig.buttonConfig = _buttonConfig;
			_defaultConfig.listInitialized = true;
			//保存模块设置信息
			sysmanMain.setModuConf(_defaultConfig.fullBizcode,_defaultConfig)
			
				
			private_method.initElement(_bizProto.pageDoc)
		},		
		
		initElement: function (doc) {		
			
			//初始化操作按钮
			_moduleConfig = sysmanMain.getCurrentModuConfig();
			var listTd = $(doc).find(_moduleConfig.btnSelector)
			
			//加载列表按钮
			if(listTd && listTd.length>0){
				var _param = {
					bizcode:_moduleConfig.fullBizcode,
					rootPath:_bizProto.rootPath,
					container:listTd,
					callback:private_method.bindBtnEvent}
				btnServ.generateListBtn(_param);
			}else{
				private_method.bindBtnEvent()
			}
			
			// 搜索框
			$searchbox=$(doc).find("input.searchbox")
			if($searchbox.length>0){
				
				var _searchParam = {
					prompt : '模糊查询',
					searcher : function(value, name) {
						var obj = {};
						obj.searchName=name;
						obj.searchValue=value;							
//						private_method.doSearch(obj)
				}}
				
				//判断search菜单是否存在
				var $searchMenu = $(doc).find("div.search-mm")
				if($searchMenu.length>0){
					_searchParam.menu=$searchMenu
				}
				$($searchbox).searchbox(_searchParam);
			}
			
			$dg = $(doc).find("table.dg-list");
			
			var _gridHeight = _bizProto.gridHeight
			if(_moduleConfig.listHeightResize){
				_gridHeight = _bizProto.gridHeight + (_moduleConfig.listHeightResize);
			}
			var _param = {
				height :_gridHeight,
				url : _bizProto.queryListUrl,
				rownumbers:true,
				pagination:_moduleConfig.pagination,
				animate: true,
				idField: 'id',				
				striped:true,
				border:true,			
//				singleSelect : true,
				fitColumns: true,
				checkOnSelect:true,
				selectOnCheck:true,
				toolbar:$(listTd)
//				title:_moduleConfig.name
			}
			
			if(_moduleConfig.querylistUrl){
				
				var _moduPath
				if(_moduleConfig.queryModule){
					_moduPath =_moduleConfig.queryModule 
				}else{
					_moduPath =_moduleConfig.moduleCode 
				}
				var _url = _bizProto.rootPath  +'/'+_moduPath +'/query/'
				_param.url = _url + _moduleConfig.querylistUrl +'.action'
			}
			var listToolBar =  $(doc).find(_moduleConfig.listToolBar)
			
			if(listToolBar.length>0){
				_param.toolbar=listToolBar
			}else{
				if(listTd.length>0){
					_param.toolbar=listTd
				}
			}
			
			//初始化元素函数
			if(_moduleConfig.initElement){
				var _initElementParam={doc:doc,rootId:_moduleConfig.rootId}
			
				$form = $(doc).find(_moduleConfig.conditionForm)
				if($form.length>0){
					_initElementParam.form = $form
				}
				_moduleConfig.initElement(_initElementParam)
			}
			
			//初始化查询条件判断
			if(_moduleConfig.initQueryParams){
				_param.queryParams=_moduleConfig.initQueryParams
			}
			
			//初始化cell点击事件
			if(_moduleConfig.cellClick){
				_param.onClickCell=_moduleConfig.cellClick
			}
			
			
			//初始化row点击事件
			if(_moduleConfig.rowClick){
				_param.onClickRow=_moduleConfig.rowClick
			}
			
			if(_moduleConfig.rowDblClick){
				_param.onDblClickRow=_moduleConfig.rowDblClick
			}
			
			var _height = $(document).height()
			if(_height && _height<750){
				_param.pageSize=10
			}
			//初始化datagrid，加载数据
			var _conditionParam = private_method.getConditionAll()
			_param.queryParams = {condition:$.extend({},_param.queryParams,_conditionParam)}
			$grid=$($dg).datagrid(_param);
			
			$.messager.progress('close');
		},
		/*
		 * 获取模糊查找框内容
		 */
		getSearchValue:function(){
			var _config = private_method.getCurrentConfig();
			var ret={};
			if(_config && _config.rootId){
				
				$searchbox = $("#"+_config.rootId +" input.searchbox")
				if($searchbox.length>0){
					var _searchName, _searchValue
					//取值
					_searchValue = $($searchbox).searchbox('getValue')
					if(_searchValue){
						_searchValue = $.trim(_searchValue)
						if(_searchValue==='')
							return
					}			
						
					//取名称
					var _searchName = $($searchbox).searchbox('getName')
					if(_searchName){
						_searchName =$.trim(_searchName)
						if(_searchName===''){
							return
						}															
					}
					
					ret[_searchName]=_searchValue;
					
					return ret
				}
				
			}
		},
		
		//获取高级查询内容
		getConditionValue:function(){
			
			var ret={}
			//获取当前模块配置
			_moduleConfig =private_method.getCurrentConfig();
			if(_moduleConfig){
					
				
				
				var _conditonParam ={}
				var _conditonFunc =_moduleConfig.conditionExtends
				//rootId是否存在
				if(_moduleConfig.rootId && 
					_moduleConfig.conditionForm){
					
					var _form = $('#'+_moduleConfig.rootId +' ' + _moduleConfig.conditionForm)
					ret = formServ.getDataObj({
						rootId:_moduleConfig.rootId,
						form : $(_form)
					});											
				}				
			}
			return ret
			 
		},
		/*
		 * 获取当前模块配置信息
		 */
		getCurrentConfig:function(){
			var _config =sysmanMain.getCurrentModuConfig();
			if(!_config){
				msgServ.Msgslide('获取模块配置信息出错')			
			}			
			return _config
		},
		
		/**
		 * 获取查询参数
		 */
		getConditionAll:function(){
			var _param={}
			//获取当前模块配置
			_moduleConfig =private_method.getCurrentConfig();			
			
			if(_moduleConfig && _moduleConfig.rootId)
				$dg= $('#'+_moduleConfig.rootId +" table.dg-list");	
			
			if($dg.length>0){
				var _tmpSearch = private_method.getSearchValue()
				var _tmpCondition = private_method.getConditionValue()
				
				_param = $.extend({},_tmpSearch,_tmpCondition)				
			}
			
			return _param
			
		},
		doSearch:function(){
			
			var _param={}
			//获取当前模块配置
			_moduleConfig =private_method.getCurrentConfig();			
			
			if(_moduleConfig && _moduleConfig.rootId)
				$dg= $('#'+_moduleConfig.rootId +" table.dg-list");	
			
			if($dg.length>0){
				_param = private_method.getConditionAll()
				if(_param && !$.isEmptyObject(_param)){
									
					$dg.datagrid('load', {condition:_param});
//					$dg.datagrid('load', _queryParam);
				}else{
//					$dg.datagrid('load');
				}
				
				
			}
		},
		
		//绑定按钮事件
		bindBtnEvent:function(){
			var _config = private_method.getCurrentConfig(),btn
			
			if(_config && _config.listToolBar){
				btn = $(_bizProto.pageDoc).find(_config.listToolBar +' a.function-btn')
			}else{
				btn = $(_bizProto.pageDoc).find(_moduleConfig.listToolBar +' a.function-btn')
			}
			// 绑定按钮事件
			
			//判断按钮是否存在
			if(btn.length>0){
				$(btn).unbind('click');
				$(btn).bind('click', private_method.function_btn_listenner)	
			}
			
			//执行查询按钮事件绑定
			if(_bizProto.rootid){
				btn = $('#'+_bizProto.rootid + ' form.condition-form a.conditon-search')
				if(btn.length>0){
					$(btn).unbind('click');
					$(btn).bind('click', private_method.function_btn_listenner)	
				}
			}
			
		},
		// 功能按钮监听函数
		function_btn_listenner : function(e) {

			btnServ.applyButton({buttonEvt:e,buttonConfig:_buttonConfig})

		},
		// 新增函数
		add : function() {
			var _config = private_method.getCurrentConfig()
			
			if(_config && _config.rootId){
				$dg= $('#'+_config.rootId +" table.dg-list");	
				$($dg).datagrid('clearSelections')
				private_method.editExecute(false);
			}
		},
		edit:function(){
			private_method.editExecute(true);
		},
		// 编辑,flag 为form按钮可见性标志
		editExecute : function(flag) {	
			if (window.console) {
				console.info( _moduleConfig.fullBizcode + ' edit on air ...');
			}
			var _config = private_method.getCurrentConfig()
			
			if(_config && _config.rootId){
				$grid= $('#'+_config.rootId +" table.dg-list");
				$edit_window = $('#' + _config.editWindow);	
				_bizProto = _config.bizProto
				
				var _url
				if(_config.editPageUrl){
					_url = _config.editPageUrl({record:$($grid).datagrid('getSelected')})
				}else{
					_url = _bizProto.flowEidtPageUrl
				}
				
				
				var _param = {grid:$grid,window:$edit_window,href:_url,width:_moduleConfig.edit_window_width,height:_moduleConfig.edit_window_height,flag:flag,existCheckElement:'form'}
				
				if(_config.onWindowClose){
					_param.onClose=_config.onWindowClose
				}
				datagridServ.windowEdit(_param);	
			}
		},
		
		// 打开或关闭高级查询栏高级
		conditionQuery : function() {
			var _queryParam = {}
			//获取当前模块配置
			_moduleConfig =private_method.getCurrentConfig();			
			
			if(_moduleConfig && _moduleConfig.rootId){
				$condition= $('#'+_moduleConfig.rootId +" div.condition")
				if($condition.length>0){
					
					var _tmp,isClosed
					var _tmpPanel = $($condition).closest('div.panel')
					isClosed=$(_tmpPanel).attr('style')				
					
					
					if(isClosed){
						isClosed = $.trim(isClosed).toLowerCase();
						_tmp = isClosed.indexOf('display: none')
						if(_tmp<0){
							$condition.panel('close')
						}else{
							$condition.panel('open')
						}
					}
						
					
				}
			}
		},
		// 删除
		del : function() {
			if(window.console){
				
				console.log('del event fired ...')
			}
			var _config = private_method.getCurrentConfig()	
			if(_config && _config.rootId){
				$grid= $('#'+_config.rootId +" table.dg-list");
				_bizProto = _config.bizProto
				datagridServ.delRow({url:_bizProto.flowDel,target:$grid,auditEnable:_config.auditEnable});
			}
			if (window.console) {
			console.info( _config.fullBizcode + ' delete on air ...');
			}
			
		},
		/**
		 * 
		 * 批量审核
		 * @param _options.status	审核状态
		 * 
		 */ 
		auditList : function(_options) {
			if(window.console){
				
				console.log('del event fired ...')
			}
			var _config = private_method.getCurrentConfig()	
			if(_config && _config.rootId){
				$grid= $('#'+_config.rootId +" table.dg-list");
				_bizProto = _config.bizProto
				datagridServ.auditList({url:_bizProto.auditListUrl,grid:$grid,status:_options.status});
			}			
			
		},
		/**
		 * 导出excel
		 * @param _options.type
		 */
		exportExcel:function(_options){
			var _param = private_method.getConditionAll()
			var _url 
			_moduleConfig =private_method.getCurrentConfig();
			
			if(_moduleConfig.querylistUrl){
				
				var _moduPath
				if(_moduleConfig.queryModule){
					_moduPath =_moduleConfig.queryModule 
				}else{
					_moduPath =_moduleConfig.moduleCode 
				}
				_url = _bizProto.rootPath  +'/'+_moduPath +'/query/' +
				  'exportExcel.action'
			}else{
				_url = _moduleConfig.bizProto.queryListUrl
			}
			if(_options && _options.type &&_options.type==='all'){
					buttonEvent.exportAll({url:_url,queryParam:_param})
					return
			}else{
				buttonEvent.exportCurrent({url:_url,queryParam:_param})
			}
			
		}
		
	}
	
	var public_method = {
		/**
		 * @param _options.doc	页面根节点
		 * @param _options.docroot	当前业务页面根节点
		 */
		init:function(_options){
			
			private_method.init(_options)
		}
	}	
	return public_method;
});